#!/usr/bin/env python
# -*- coding: UTF-8 -*-

# to play subtitles properly add -subpos 90 -spualign 2 -spuaa 4 to mplayer


class file:
	def __init__ (self,device):
		import commands
		self.device 	= device
		self.tipo	= 'dvd'
		self.titleNum	= 0
		self.titles = {}
		tmpFileType = commands.getstatusoutput('file "' + self.device + '"')[-1]
		print tmpFileType
		if ('directory' not in tmpFileType) or ('ISO' not in tmpFileType):
			self.tipo  = 'file'
	def clear(self):
		import commands
		self.tipo	= 'file'
		self.titleNum	= 0
		self.titles = {}
		tmpFileType = commands.getstatusoutput('file "' + self.device + '"')[-1]
		print tmpFileType
		if ('directory' in tmpFileType) or ('UDF' in tmpFileType) or (self.device[:5] == "/dev/"):
			self.tipo  = 'dvd'
		
	def load(self,title = ''):
		import commands,sys
		from re import search
		if self.tipo == 'dvd':
			cmd = 'mplayer -identify dvd://' + str(title) + ' -dvd-device "' + str(self.device)+ '" -frames 1 -v -vo null'
			print "### ", cmd
			self.data = commands.getstatusoutput(cmd)[-1] 
			if "Reading disc structure" not in self.data: 
				self.nodata = 1
			else:
				if self.titleNum == 0:
					#print self.data
					try:
						self.titleNum = search ("ID_DVD_TITLES=(\d+)", self.data).groups()[0]
					except:
						pass
					for i in range(1,int(self.titleNum)+1):
						self.titles[i] = {}
						self.titles[i]['scanned'] = 0
						self.titles[i]['chapNum'] = search ("ID_DVD_TITLE_"+str(i)+"_CHAPTERS=(\d+)", self.data).groups()[0]
						self.titles[i]['angulos'] = search ("ID_DVD_TITLE_"+str(i)+"_ANGLES=(\d+)", self.data).groups()[0]
						try:
							self.titles[i]['duracion'] = int(search ("ID_DVD_TITLE_"+str(i)+"_LENGTH=(\d+)", self.data).groups()[0])
						except:
							pass
					#print self.titles.keys()
				if title <> '' : 
					self.titles[int(title)]['scanned'] = 1
					self.titles[int(title)]['vid'] = {}
					try:
						videoStuff(self.titles[int(title)]['vid'], self.data)	
					except:
						pass

					self.titles[int(title)]['aid'] = {}
					self.titles[int(title)]['sid'] = {}
					for i in self.data.split('\n'):
						if 'aid' in i:
							try:
								#print [i]
								tmp = search(': (\d+) .*?: (\w+) \((.*?)\) .*?: (\w+) aid: (\d+).',i).groups()
								self.titles[int(title)]['aid'][int(tmp[0])] = {'id':tmp[0], 'formato':tmp[1], 'ch':tmp[2],'idioma':tmp[3] ,'aid':tmp[4]} 
							except:
								pass
						if 'sid' in i:
							try:
								#print [i]
								tmp = search(': (\d+) .*?: (\w+)',i).groups()
								#print tmp
								if int(tmp[0]) not in self.titles[int(title)]['sid'].keys():
									self.titles[int(title)]['sid'][int(tmp[0])] = {'id':tmp[0], 'idioma':tmp[1]}
								
							except:
								pass
					# AUDIO EXTRA DATA
					for i in self.titles[int(title)]['aid'].keys():
						cmd = 'mplayer -identify dvd://' + str(title) + ' -dvd-device "' + str(self.device)+ '" -frames 0 -v -aid '+ self.titles[int(title)]['aid'][i]['aid']
						print "### ", cmd
						self.data = commands.getstatusoutput(cmd)[-1] 
						audioStuff(self.titles[int(title)]['aid'][i],self.data)
			if self.titles.has_key(int(title)):
				for i in self.titles[int(title)].keys():
					if i == 'aid' or i == 'sid':
						for j in self.titles[int(title)][i].keys():
							print "\t[",i,"][",j,"]",self.titles[int(title)][i][j]
					else:
						print "[",i,"]",self.titles[int(title)][i]


		if self.tipo == 'file':
			mkvCmd = 'mkvmerge -i ' + self.device
			self.data = commands.getstatusoutput(mkvCmd)[-1]
			mkvDesp = int(search ('Track ID (\d+)', self.data).groups()[0])
			print [mkvDesp]
			cmd = 'ffmpeg -i "' + str(self.device).replace("idx","sub") + '"'
			self.data = commands.getstatusoutput(cmd)[-1]
			print "### file ###", cmd, "\n", self.data
			self.vid = {}
			self.aid = {}
			self.sid = {}
			mkvId = 0
			for i in self.data.split('\n'):
				print [i]
				id = ''
				tipo = ''
				lang = 'und'
				datos = ''
				try:	
					elem = search ('Stream #0\.(\d{1})\((.*)\): (.*): (.*)',i).groups()
					id = int(elem[0]) + mkvDesp
					lang = elem[1]
					tipo = elem[2]
					datos = elem[3]
					print id, lang, tipo, datos
				except:
					try:
						elem = search ('Stream #0\.(\d{1}): (.*): (.*)',i).groups()
						id = int(elem[0]) + mkvDesp
						tipo = elem[1]
						datos = elem[2]
						print id, tipo, [datos]
					except:
						try:
							elem = search ('Stream .* (Subtitle): (dvdsub)',i).groups()
							id = mkvDesp
							tipo = elem[0]
							datos = elem[1]
							print id, tipo, [datos]
						except:
							print "ERROR"
							pass
			#Stream #0.0(spa): Subtitle: dvdsub
			#Stream #0.1(eng): Subtitle: dvdsub
			#Stream #0.2(spa): Audio: aac, 48000 Hz, 5.1, s16
			#Stream #0.3(eng): Audio: vorbis, 44100 Hz, 5.1, s16
			#Stream #0.4: Video: h264, yuv420p, 704x560, PAR 91:64 DAR 143:80, 25.00 tb(r)

				if tipo == 'Subtitle': 
					self.sid[id] = {'mkvId':id,'idioma':lang,'codec':''}
				elif tipo == 'Audio':
					codec = datos.split(',')[0]
					rate = 	datos.split(',')[1]
					ch = 	datos.split(',')[2]
					self.aid[id] = {'mkvId':id, 'acodec':'','id':id, 'idioma':lang, 'ch':ch, 'codec':codec, 'format':'', 'rate':rate, 'bitrate':''}

				elif tipo == 'Video':
					#Stream #0.0(und): Video: mpeg4, yuv420p, 176x144 [PAR 16:11 DAR 16:9], 25.00 tb(r)'
					codec = datos.split(',')[0]
					format =datos.split(',')[1]
					ancho = search ('(\d*)x\d*',datos.split(',')[2]).groups()[0] 
					alto = 	search ('\d*x(\d*)',datos.split(',')[2]).groups()[0]
					fps = 	datos.split(',')[-1][:-6]
					self.vid[id] = {'mkvId':id, 'id':id, 'codec':codec, 'format':format, 'ancho':ancho, 'alto':alto, 'aspect':'', 'fps':fps}	
					

			if self.device[-3:] == "srt":
				self.sid[0] = {'mkvId':'0','idioma':'und','codec':'srt'}

			for i in self.vid.keys():
				self.data = commands.getstatusoutput('mplayer -identify "' + str(self.device) + '" -frames 0 -v -vid '+str(i))[-1]
				videoStuff(self.vid[i],self.data)
			for i in self.aid.keys():
				self.data = commands.getstatusoutput('mplayer -identify "' + str(self.device) + '" -frames 0 -v -aid '+str(i))[-1]
				audioStuff(self.aid[i],self.data)

		
def videoStuff(dic,data):
	from re import search
	for i in data.split('\n'):
		try:
			dic['chapters'] = search ("CHAPTERS: (.*)"		, i).groups()[0][:-1].split(',')
		except:
			pass
		try:
			dic['bitrate'] 	= search ("ID_VIDEO_BITRATE=(\d+)"	, i).groups()[0]
		except:
			pass
		try:
			dic['aspect'] 	= search ("ID_VIDEO_ASPECT=(\d+\.\d+)"	, i).groups()[0]
		except:
			pass
		#try:
		#	dic['fps'] 	= search ("ID_VIDEO_FPS=(\d+\.\d+)"	, i).groups()[0]
		#except:
		#	pass

def audioStuff(dic, data):
	from re import search
	for i in data.split('\n'):
		try:
			dic['format'] 	= search ("ID_AUDIO_FORMAT=(\w+)", i).groups()[0]
		except:
			pass
		try:
			dic['bitrate'] 	= search ("ID_AUDIO_BITRATE=(\d+)", i).groups()[0]
		except:
			pass

from sys import argv
if __name__ == '__main__':
	a = file (argv[1])
	if len(argv) == 3:
		a.load(argv[2])
	else:
		a.load()
	if a.tipo == 'file':
		for i in a.sid.keys():
			print 'sid',a.sid[i]
		for i in a.aid.keys():
			print 'aid',a.aid[i]
		for i in a.vid.keys():
			print 'vid',a.vid[i]
	else:
		for i in a.titles.keys():
			if 'duracion' in a.titles[i].keys():print "capitulo:", i, 'duradion',a.titles[i]['duracion']
			else: print "capitulo:", i 
			if 'vid' in a.titles[i].keys():
				print a.titles[i]['vid']
				for j in a.titles[i]['aid'].keys():
					print a.titles[i]['aid'][j]
				for j in a.titles[i]['sid'].keys():
					print a.titles[i]['sid'][j]
		
